<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @copyright   Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
 /** @var $this \Magento\ConfigurableProduct\Block\Adminhtml\Product\Edit\Tab\Super\Config */

use \Magento\ConfigurableProduct\Model\Product\Type\Configurable;
?>
<div class="entry-edit form-inline" id="<?php echo $this->getId() ?>">
    <div class="fieldset-wrapper collapsable-wrapper" id="<?php echo $this->getId() ?>-wrapper" data-panel="product-variations">
        <div class="fieldset-wrapper-title">
            <strong class="title" data-toggle="collapse" data-target="#<?php echo $this->getId() ?>-content">
                <span><?php echo __('Variations') ?></span>
            </strong>
        </div>

        <div class="fieldset-wrapper-content collapse" id="<?php echo $this->getId() ?>-content">
            <fieldset class="fieldset">
                <div class="field" id="variations-search-field">
                    <label class="label" for="configurable-attribute-selector"><span>Search</span></label>
                    <div class="control">
                        <input type="text" id="configurable-attribute-selector" class="input-text search"
                               placeholder="start typing to search attribute" title="Select Attribute"
                               autocomplete="off"/>
                    </div>
                    <?php echo $this->getChildHtml('add_attribute'); ?>
                </div>

                <?php echo $this->getChildHtml('generator'); ?>

                <!-- Select Associated Product popup -->
                <div id="associated-products-container">
                    <?php echo $this->getGridHtml(); ?>
                </div>

                <input type="hidden" name="affect_configurable_product_attributes" value="1" />
            </fieldset>
        </div>
    </div>
</div>
<script type="text/javascript">
require([
    'jquery',
    'jquery/ui',
    'jquery/jquery.tabs',
    'mage/mage',
    'mage/backend/menu',
    'Magento_ConfigurableProduct/catalog/product-variation'
], function($){
    'use strict';

    var variationsContainer = $("#<?php echo $this->getId()?>"),
        collapsableWrapper = $("#<?php echo $this->getId()?>-wrapper"),
        collapsableArea = $('> .collapse', collapsableWrapper),
        stockAvailabilityField = $('#quantity_and_stock_status'),
        qtyField = $('#qty'),
        currentProductTemplateControl = $('#product-template-suggest-container .action-dropdown > .action-toggle'),
        attributesInput = $("input[name='attributes[]']", variationsContainer),
        hasVariations = <?php echo ($this->getProduct()->getTypeId() == Configurable::TYPE_CODE || $this->getRequest()->has('attributes')) ? 'true' : 'false' ?>,
        isLocked = function (element) {
            return element.is('[data-locked]');
        },
        disableElement = function (element) {
            if (!isLocked(element)) {
                element.prop('disabled', true).trigger('change');
            }
        },
        enableElement = function (element) {
            if (!isLocked(element)) {
            element.removeProp('disabled').trigger('change');

            }
        };

    collapsableArea
        .on('show', function() {
            currentProductTemplateControl
                .addClass('disabled')
                .prop('disabled', true);

            attributesInput.prop('disabled', false);

            disableElement(qtyField);
            enableElement(stockAvailabilityField);

            $.each($.mage.variationsAttributes($('#configurable-attributes-container')).getAttributes(), function() {
                $('#attribute-' + this.code + '-container select').prop('disabled', true);
            })
        })
        .on('hide', function() {
            if ($.mage.variationsAttributes($('#configurable-attributes-container')).getAttributes().length) {
                return;
            }
            currentProductTemplateControl
                .removeClass('disabled')
                .removeProp('disabled');

            disableElement(stockAvailabilityField);
            enableElement(qtyField);
        })
        .collapse(hasVariations ? 'show' : 'hide');

    var $gridDialog = $('#associated-products-container').dialog({
        title: 'Select Associated Product',
        autoOpen: false,
        minWidth: 980,
        modal: true,
        resizable: true
    });

    $('[data-panel=product-variations]')
        .on('generate', '[data-role=product-variations-matrix]', function(event, data) {
            var form = $('[data-form=edit-product]');
            if (!form.valid()) {
                form.data('validator').focusInvalid();
                return;
            }
            $.ajax({
                url: data.url,
                data: form.serialize(),
                dataType: 'html',
                context: variationsContainer,
                showLoader: true
            }).success(function(data) {
                $('[data-role=product-variations-generator]').html(data).trigger('contentUpdated');
                $('#product_type_id').val('configurable').trigger('change');
            });
        })
        .on('add-option', '[data-action=add-option]', function(event) {
            var attributeContainer = $(event.target).closest('[data-role=configurable-attribute]'),
                panel = attributeContainer.closest('[data-panel=product-variations]'),
                newOptionsCount = attributeContainer.data('newOptionsCount') || 0,
                attribute = attributeContainer.data('attribute');
            attributeContainer.find('[data-role=options]')
                .append(
                    panel.find('[data-template-for=new-option]').tmpl({
                        attribute: {id: attribute.attribute_id || attribute.id},
                        option: {id: 'new-option-' + newOptionsCount}
                    })
                )
                .trigger('contentUpdated');
            attributeContainer.data('newOptionsCount', ++newOptionsCount);
        })
        .on('disable', '[data-role=product-variations-matrix]', function() {
            $(this).html('');
        })
        .on('click', '[data-column=entity_id]', function() {
            var entityCheckBox = $(this);
            entityCheckBox.closest('tr').find('input[type!=checkbox],button').each(function () {
                if (!isLocked($(this))) {
                    $(this).prop('disabled', !entityCheckBox.is(':checked'));
                }
            });
        })
        .on('click', '[data-action=choose]', function(event) {
            event.preventDefault();
            var grid = window.<?php echo $this->getGridJsObject() ?>;
            var $button = $(this);
            var attributeIds = [];
            variationsContainer.find("input[name='attributes[]']").each(function () {
                attributeIds.push($(this).val());
            });

            grid.reloadParams = {
                filter: $button.data('attributes'),
                'attributes[]': attributeIds
            };
            grid.reload(null, function() {
                $gridDialog.dialog('open')
            });

            grid.rowClickCallback = function(grid, event) {
                if (!this.rows || !this.rows.length) {
                    return;
                }
                var $gridRow = $(event.target).closest('tr'),
                    columnSelectorTemplate = '[data-column="%s"]';

                if ($gridRow.find(columnSelectorTemplate.replace('%s', 'entity_id')).length) {
                    var $matrixRow = $button.parents('[data-role=row]');

                    $.each('name,sku,qty,weight,entity_id'.split(','), function () {
                        var columnSelector = columnSelectorTemplate.replace('%s', this),
                            target = $matrixRow.find(columnSelector),
                            value = $.trim($gridRow.find(columnSelector).text()),
                            button = target.find('[data-action=choose]');

                        target[target.is('input[type=checkbox]') ? 'val' : 'text'](value).append(button);
                    });

                    $matrixRow.find(columnSelectorTemplate.replace('%s', 'entity_id'))
                        .prop({checked: true, disabled: false});

                    $matrixRow.find('[data-action=no-image]').trigger('click');

                    var parentElement = $matrixRow.find('[data-column=image]'),
                        uploaderControl = parentElement.find('[data-action=upload-image]', parentElement),
                        imageElement = $matrixRow.find('[data-role=image]');

                    if (imageElement.length) {
                        imageElement.attr('src', $gridRow.find('[data-role=image-url]').val());
                    } else {
                        var matrix = $('[data-role=product-variations-matrix]');
                        $.tmpl(matrix.find('[data-template-for=variation-image]').html(), {
                            url: $gridRow.find('[data-role=image-url]').val()
                        }).prependTo(uploaderControl);
                    }

                    $matrixRow.find('[name=image]')
                        .attr('src', $gridRow.find('[data-role=image-url]').val())
                        .attr('data-locked', '1')
                        .trigger('click')
                        .prop({disabled: true});

                    $matrixRow.find('[name$="[image]"]').remove();
                }
                $gridDialog.dialog('close');
            };
        });
});
</script>
